#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id: admin.py 146 2009-08-11 13:09:30Z doug.hellmann $"

# Import system modules
import logging
import os
from cStringIO import StringIO

# Import third-party modules
from django import http
from django import template
from django.conf import settings
import django.contrib.admin.views.main as admin_views
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required, permission_required
from django import newforms
from django.shortcuts import render_to_response
from django.views.decorators.cache import never_cache

# Import local modules
from docket.vtr_loader import load_data_from_stream, ErrorKeeper
from docket.models import Case, MediaFile

# Module

logger = logging.getLogger('docket.admin')

@permission_required('docket.case.can_add', login_url="/admin/")
def upload_vtr(request):
    logger.debug('upload_vtr')
    template_args = {
        'title':'Load VTR Data',
        'existing':0,
        'new':0,
        'output':'',
        'errors':[],
        'num_errors':0,
        'filename':'',
        }
    if request.method == 'POST':
        try:
            vtr_data = request.FILES['vtr_data']
        except KeyError:
            # Use the default arguments
            pass
        else:
            logger.debug(vtr_data)
            
            # Save the file
            archive_name = os.path.join(settings.VTR_ARCHIVE_DIR, os.path.basename(vtr_data['filename']))
            logger.debug('archiving to %s', archive_name)
            f = open(archive_name, 'wt')
            try:
                f.write(vtr_data['content'])
            finally:
                f.close()
            
            # Load the data from the uploaded file
            stream = StringIO(vtr_data['content'])
            out_buffer = StringIO()
            errors = ErrorKeeper()
            counts = load_data_from_stream(stream, message_stream=out_buffer, errorcb=errors)
        
            # Massage the error text
            for e in errors.errors:            
                e['body'] = '\n'.join('%5d: %s' % (n+e['start'], l)
                                    for (n, l) in enumerate(e['lines']))
            
            template_args = {
                'title':'Load VTR Data',
                'existing':counts[0],
                'new':counts[1],
                'output':out_buffer.getvalue(),
                'errors':errors.errors,
                'num_errors':len(errors.errors),
                'filename':vtr_data['filename'],
                }

    return render_to_response('load_vtr.html', template_args)


class MediaFileUploadForm(newforms.Form):
    case_year = newforms.IntegerField()
    case_num = newforms.IntegerField()
    title = newforms.CharField()
    citation = newforms.CharField()
    image = newforms.ImageField()

@permission_required('docket.mediafile.can_add', login_url="/admin/")
def add_mediafile(request):
    logging.debug('add_mediafile POST=%s FILES=%s', request.POST, request.FILES)
    
    if request.POST:
        form = MediaFileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            logging.debug('form is valid')
            case = Case.objects.get(year=form.cleaned_data['case_year'], 
                                    num=form.cleaned_data['case_num'],
                                    )
            new_mediafile = MediaFile(case=case,
                                      title=form.cleaned_data['title'],
                                      citation=form.cleaned_data['citation'],
                                      )
            filename = form.cleaned_data['image'].filename
            file_contents = form.cleaned_data['image'].content
            new_mediafile.save_image_file(filename, file_contents)
            new_mediafile.save()
        else:
            logging.debug('form has errors %s', form.errors)
        
    else:
        form = MediaFileUploadForm()
    
        
    template_args = dict(
        form=form,
        first_form_field_id='id_case_year',
        opts=MediaFile._meta,
        )
    return render_to_response('add_mediafile.html', template_args)

